<template>
  <div id="container" ref="container">
    <el-table
      :data="tableData"
      :header-cell-style="headClass"
      :cell-style="tableClass"
      style="width: 100%"
    >
      <el-table-column fixed="left" prop="name" label="姓名" width="230"></el-table-column>
      <el-table-column prop="mobile" label="手机号码"></el-table-column>
      <el-table-column prop="power" label="数据查看范围" width="380"></el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEditYes(scope.$index,scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="handleEditNo(scope.$index,scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pager">
      <el-pagination
        small
        background
        layout="prev ,pager,next"
        :total="pagesizeCount"
        :pager-count="5"
        :page-size="pagesize"
        :current-page.sync="currpage"
        @current-change="getNewlist(currpage)"
      ></el-pagination>
    </div>
    <div style="text-align:right;margin-top:6px;">
      <el-button type="primary" @click="dialogFormVisible=true,operation='add'">新增+</el-button>
    </div>
    <!------------------------弹出框------------------------------>
    <el-dialog
      title="填写信息"
      :visible.sync="dialogFormVisible"
      center
      @close="notSubmit('okForm')"
      :width="diaWidth"
    >
      <el-form
        style="padding:0 20px;"
        label-width="auto"
        :rules="rules"
        label-position="left"
        :model="okForm"
        ref="okForm"
      >
        <el-form-item label="可查数据" prop="module">
          <el-select
            v-model="okForm.module"
            placeholder="请选择部门"
            style="-webkit-tap-highlight-color: transparent;"
          >
            <el-option
              v-for="(item,i) in bmType"
              :key="item"
              :label="--i+':'+item"
              :value="i.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="okForm.phone" onkeyup="this.value=this.value.replace(/^\s+|\s+$/g,'')"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="okForm.password"
            show-password
            onkeyup="this.value=this.value.replace(/^\s+|\s+$/g,'')"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input
            placeholder="请再次输入密码"
            v-model="okForm.password2"
            show-password
            onkeyup="this.value=this.value.replace(/^\s+|\s+$/g,'')"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="okForm.name" onkeyup="this.value=this.value.replace(/^\s+|\s+$/g,'')"></el-input>
        </el-form-item>
        <el-form-item id="buttonbox" style="text-align:center;">
          <el-button @click="notSubmit('okForm')">取消</el-button>
          <el-button type="primary" @click="okSubmit('okForm')">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 密码
    var validateNumber = (rule, value, callback) => {
      if (this.okForm.password.trim() == "") {
        callback(new Error("请输入密码"));
      } else if (this.okForm.password.trim().toString().length < 6) {
        callback(new Error("密码长度应在6位数以上"));
      } else {
        callback();
      }
    };
    // 确认密码
    var validateNumber1 = (rule, value, callback) => {
      if (this.okForm.password2.trim() == "") {
        callback(new Error("请再次输入密码"));
      } else if (this.okForm.password2 !== this.okForm.password) {
        callback(new Error("密码输入不一致"));
      } else {
        callback();
      }
    };
    //验证数字
    var validateNumber2 = (rule, value, callback) => {
      if (this.okForm.username.trim() == "" || isNaN(this.okForm.username)) {
        callback(new Error("请输入正确的学号"));
      } else if (this.okForm.username.trim().toString().length !== 11) {
        callback(new Error("学号长度应为11位,且不能含有空格"));
      } else {
        callback();
      }
    };
    //手机号
    var validateNumber3 = (rule, value, callback) => {
      const reg = /^1([38]\d|5[0-35-9]|7[3678])\d{8}$/;
      if (!reg.test(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    return {
      dialogFormVisible: false,
      operation: "", //判断 add 或 update 操作
      diaWidth: "500px", //diaing弹出框宽度
      okForm: {
        //弹出框数据
        id: "",
        password: "",
        password2: "",
        name: "",
        phone: "",
        module: ""
      },
      powerbm: "", //暂存部门权限值
      tableData: [], //人员列表
      bmType: [], //部门
      currpage: 1, //当前页码
      pagesize: 10, //每页展示数目
      pagesizeCount: 0, //总条数
      rules: {
        password: [
          { required: true, validator: validateNumber, trigger: "blur" }
        ],
        password2: [
          { required: true, validator: validateNumber1, trigger: "blur" }
        ],
        phone: [
          { required: true, validator: validateNumber3, trigger: "blur" }
        ],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        module: [
          { required: true, message: "请选择负责模块", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.$axios
      .get("/api/getBmStrList")
      .then(res => {
        this.bmType = res.data.data;
        this.bmType.unshift('系统管理员','全校数据');
        this.getPerlist();
      })
      .catch(err => {
        console.log(err);
      });
  },
  methods: {
    //获取人员列表
    getPerlist() {
      this.$axios
        .get("/api/user/queryList")
        .then(res => {
          res.data.data.forEach(item => {
            let i = item.power;
            item.power = i + ":" + this.bmType[++i];
          });
          this.tableData = res.data.data;
        })
        .catch(err => {
          console.log(err);
        });
    },
    //切换页数
    getNewlist(cpage) {
      this.currpage = cpage;
    },
    // 表头样式设置
    headClass() {
      return "text-align: center;";
    },
    // 单元格样式
    tableClass() {
      return "text-align: center;";
    },
    setInput(mail) {
      this.inputEmail = mail;
    },
    //操作事件 修改
    handleEditYes(index, row) {
      this.operation = "update";
      this.okForm.id = row.id;
      this.okForm.password = row.password;
      this.okForm.password2 = row.password;
      this.okForm.module = row.power;
      this.okForm.name = row.name;
      this.okForm.phone = row.mobile;
      this.dialogFormVisible = true;
    },
    // 删除
    handleEditNo(index, row) {
      this.$confirm("确定要 删除 吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      }).then(() => {
        this.$axios
          .get("/api/user/deleteById/" + row.id)
          .then(res => {
            if (res.data.code == "0000") {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.tableData.splice(index, 1);
            }
          })
          .catch(err => {
            this.$alert("删除失败,请稍后重试!", {
              confirmButtonText: "确定",
              center: true
            });
          });
      });
    },
    //确认信息
    okSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let PramsData = {
            id: this.okForm.id,
            password: this.okForm.password,
            power:
              this.okForm.module.length == 2
                ? this.okForm.module.substring(0, 2)
                : this.okForm.module.substring(0, 1) || "",
            name: this.okForm.name,
            mobile: this.okForm.phone
          };
          if (this.operation == "add") {
            this.$axios
              .post("/api/user/add?", PramsData)
              .then(res => {
                if (res.data.code == "0000") {
                  this.dialogFormVisible = false;
                  this.$refs[formName].resetFields();
                  this.$alert("新增成功!", {
                    confirmButtonText: "确定",
                    center: true
                  });
                  this.getPerlist();
                } else {
                  this.$alert("新增失败：" + res.data.msg, {
                    confirmButtonText: "确定",
                    center: true
                  });
                }
              })
              .catch(err => {
                this.$alert("网络异常,请稍后再试!", {
                  confirmButtonText: "确定",
                  center: true
                });
              });
          } else if (this.operation == "update") {
            this.$axios
              .post("/api/user/update", PramsData)
              .then(res => {
                if (res.data.code == "0000") {
                  this.dialogFormVisible = false;
                  this.$refs[formName].resetFields();
                  this.$alert("修改成功!", {
                    confirmButtonText: "确定",
                    center: true
                  });
                  this.getPerlist();
                } else {
                  this.$alert("修改失败：" + res.data.msg, {
                    confirmButtonText: "确定",
                    center: true
                  });
                }
              })
              .catch(err => {
                this.$alert("网络异常,请稍后再试!", {
                  confirmButtonText: "确定",
                  center: true
                });
              });
          }
        } else {
          return false;
        }
      });
    },
    //取消按钮
    notSubmit(formName) {
      this.dialogFormVisible = false;
      this.$refs["okForm"].resetFields();
      this.okForm = {
        id: "",
        password: "",
        password2: "",
        name: "",
        phone: "",
        module: ""
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.container {
  .pager {
    text-align: center;
    margin-top: 14px;
  }
  #buttonbox {
    /deep/ .el-form-item__content {
      margin-left: 0 !important;
    }
  }
}
</style>